import express from 'express';
import path from 'path';
import cors from 'cors';
import { fileURLToPath } from 'url';

const app = express();
const PORT = process.env.PORT || 3000;

// 解决 __dirname 在 ES 模块中的问题
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 中间件配置
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use(express.static(path.join(__dirname, 'dist'))); // 改为 dist 目录，因为 Vue 构建输出在 dist

// 模拟数据库数据
const products = [
    {
        id: 1,
        name: '无线蓝牙耳机',
        price: 399,
        category: '配件',
        image: 'headphones.jpg'
    },
    {
        id: 2,
        name: '快充充电器',
        price: 199,
        category: '配件',
        image: 'charger.jpg'
    },
    {
        id: 3,
        name: '手机保护壳',
        price: 89,
        category: '配件',
        image: 'phone_case.jpg'
    },
    {
        id: 4,
        name: '移动电源',
        price: 159,
        category: '配件',
        image: 'power_bank.jpg'
    },
    {
        id: 5,
        name: '智能手机',
        price: 2999,
        category: '手机',
        image: 'smartphone.jpg'
    },
    {
        id: 6,
        name: '笔记本电脑',
        price: 5999,
        category: '笔记本',
        image: 'laptop.jpg'
    }
];

// API路由
app.get('/api/products', (req, res) => {
    const { category } = req.query;
    if (category) {
        const filteredProducts = products.filter(product => product.category === category);
        res.json(filteredProducts);
    } else {
        res.json(products);
    }
});

app.get('/api/products/:id', (req, res) => {
    const product = products.find(p => p.id === parseInt(req.params.id));
    if (product) {
        res.json(product);
    } else {
        res.status(404).json({ message: '产品未找到' });
    }
});

app.get('/api/categories', (req, res) => {
    const categories = [...new Set(products.map(product => product.category))];
    res.json(categories);
});

// 健康检查
app.get('/health', (req, res) => {
    res.json({
        status: 'OK',
        timestamp: new Date().toISOString()
    });
});

// SPA 支持 - 避免使用通配符路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`🚀 服务器运行在 http://localhost:${PORT}`);
    console.log('📚 可用接口:');
    console.log(`   GET /api/products - 获取所有产品`);
    console.log(`   GET /api/products?category=配件 - 按分类筛选`);
    console.log(`   GET /api/products/:id - 获取单个产品`);
    console.log(`   GET /api/categories - 获取所有分类`);
    console.log(`   GET /health - 健康检查`);
});

export default app;